"""
设备管理应用表单
"""
from django import forms
from django.core.exceptions import ValidationError
from .models import Device, DeviceBrand, DeviceType, PlatformCredential


class DeviceForm(forms.ModelForm):
    """设备表单"""
    
    class Meta:
        model = Device
        fields = ['name', 'brand', 'device_type', 'device_id', 'room', 'is_active']
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入设备名称'
            }),
            'brand': forms.Select(attrs={
                'class': 'form-select'
            }),
            'device_type': forms.Select(attrs={
                'class': 'form-select'
            }),
            'device_id': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入设备ID'
            }),
            'room': forms.Select(attrs={
                'class': 'form-select'
            }),
            'is_active': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            }),
        }
        labels = {
            'name': '设备名称',
            'brand': '设备品牌',
            'device_type': '设备类型',
            'device_id': '设备ID',
            'room': '房间位置',
            'is_active': '启用设备',
        }

    def clean_device_id(self):
        """验证设备ID"""
        device_id = self.cleaned_data.get('device_id')
        if device_id:
            # 检查设备ID是否已存在（排除当前编辑的设备）
            queryset = Device.objects.filter(device_id=device_id)
            if self.instance.pk:
                queryset = queryset.exclude(pk=self.instance.pk)
            if queryset.exists():
                raise ValidationError("该设备ID已存在")
        return device_id


class DeviceBrandForm(forms.ModelForm):
    """设备品牌表单"""
    
    class Meta:
        model = DeviceBrand
        fields = ['name', 'api_endpoint', 'auth_type', 'logo', 'description', 'is_active']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入品牌名称'}),
            'api_endpoint': forms.URLInput(attrs={'class': 'form-control', 'placeholder': 'https://api.example.com'}),
            'auth_type': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '如：OAuth2, API Key等'}),
            'logo': forms.FileInput(attrs={'class': 'form-control', 'accept': 'image/*'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': '请输入品牌描述'}),
            'is_active': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }
        labels = {
            'name': '品牌名称',
            'api_endpoint': 'API端点',
            'auth_type': '认证类型',
            'logo': '品牌Logo',
            'description': '品牌描述',
            'is_active': '启用品牌',
        }


class DeviceTypeForm(forms.ModelForm):
    """设备类型表单"""
    
    class Meta:
        model = DeviceType
        fields = ['name', 'category', 'supported_commands', 'icon', 'description']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入设备类型名称'}),
            'category': forms.Select(attrs={'class': 'form-select'}),
            'supported_commands': forms.Textarea(attrs={
                'class': 'form-control', 
                'rows': 4, 
                'placeholder': '请输入JSON格式的命令列表，如：["power_on", "power_off", "set_temperature"]'
            }),
            'icon': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '如：fas fa-thermometer-half'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3, 'placeholder': '请输入类型描述'}),
        }
        labels = {
            'name': '设备类型名称',
            'category': '设备分类',
            'supported_commands': '支持的命令',
            'icon': '图标类名',
            'description': '类型描述',
        }
    
    def clean_supported_commands(self):
        """验证支持的命令格式"""
        supported_commands = self.cleaned_data.get('supported_commands')
        if supported_commands:
            try:
                if isinstance(supported_commands, str):
                    import json
                    json.loads(supported_commands)
            except json.JSONDecodeError:
                raise ValidationError("命令格式不正确，请输入有效的JSON格式")
        return supported_commands


class PlatformCredentialForm(forms.ModelForm):
    """平台凭证表单"""
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control'}),
        label='平台密码',
        help_text='密码将被加密存储'
    )
    
    class Meta:
        model = PlatformCredential
        fields = ['brand', 'platform_username', 'additional_data', 'is_active']
        widgets = {
            'brand': forms.Select(attrs={'class': 'form-select'}),
            'platform_username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入平台用户名'}),
            'additional_data': forms.Textarea(attrs={
                'class': 'form-control', 
                'rows': 3, 
                'placeholder': '请输入JSON格式的额外认证数据，如：{"app_id": "xxx", "secret": "xxx"}'
            }),
            'is_active': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }
        labels = {
            'brand': '设备品牌',
            'platform_username': '平台用户名',
            'additional_data': '额外认证数据',
            'is_active': '启用凭证',
        }
    
    def clean_additional_data(self):
        """验证额外数据格式"""
        additional_data = self.cleaned_data.get('additional_data')
        if additional_data:
            try:
                if isinstance(additional_data, str):
                    import json
                    json.loads(additional_data)
            except json.JSONDecodeError:
                raise ValidationError("数据格式不正确，请输入有效的JSON格式")
        return additional_data
    
    def save(self, commit=True):
        """保存时加密密码"""
        instance = super().save(commit=False)
        password = self.cleaned_data.get('password')
        if password:
            # 这里应该使用加密方法，暂时直接存储
            instance.platform_password = password
        if commit:
            instance.save()
        return instance